package com.sgb.goods.viewmodel.publish;

import androidx.lifecycle.MutableLiveData;

import com.sgb.goods.api.GoodsCallBack;
import com.sgb.goods.api.GoodsNet;
import com.sgb.goods.entity.AlbumEntity;
import com.sgb.goods.utils.base.viewmodel.BaseViewModel;
import com.sgb.goods.view.adapter.publish.ImageAdapter;
import com.swgk.core.base.model.entity.BaseEntity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 商品发布-图片上传
 * 在发布的时候进行图片上传
 * @author cyj
 */
public class ImageUploadViewModel extends BaseViewModel {

    public ImageAdapter imageAdapter;
    /** 当前上传图片的下标 */
    public int currentImgNum = 0;
    /** 多张图片上传(递归单张上传)。上传回传的文件服务器图片地址，注意有时候图片地址返回没有域名 */
    public List<String> uploadImgUrlList = new ArrayList<>();
    // 上传成功的图片地址
    public MutableLiveData<List<String>> uploadImgUrlLD = new MutableLiveData<>();

    public ImageUploadViewModel() {
        imageAdapter = new ImageAdapter(8);
    }

    /** 上传多图片 */
    public void uploadImage(int completeNum) {
        if(1 == completeNum) {
            // 首次调用，从第一张开始、清除集合内容以及重置当前上传文件下标
            uploadImgUrlList.clear();
            currentImgNum = 0;
        }
        AlbumEntity albumEntity = imageAdapter.getData().get(currentImgNum);
        File file = new File(albumEntity.imageUrl);
        Map<String, RequestBody> photos = new HashMap<>();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"" + completeNum + "image.jpg", requestBody);
        showLoading();
        GoodsNet.getInstance().getGoodsPublishApi().uploadFile(photos).enqueue(new GoodsCallBack<BaseEntity<Object>>() {
            @Override
            public void onSuccess(BaseEntity<Object> data) {
                uploadImgUrlList.add(data.getData().toString());
                if(currentImgNum + 1 == imageAdapter.getDataSize()) {
                    uploadImgUrlLD.setValue(uploadImgUrlList);
                } else {
                    ++ currentImgNum;
                    uploadImage(currentImgNum + 1);
                }
            }
        });
    }
}
